package org.suren.littlebird.preferences;

import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.List;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.dialogs.ContainerSelectionDialog;

/**
 * @author suren
 * @date 2015-4-3
 *
 * http://surenpi.com
 */
public class SuRenFileSyncPreferencePage extends PreferencePage
	implements IWorkbenchPreferencePage
{
	private Button addBut;
	private Button removebut;
	private List	syncList;

	@Override
	public void init(IWorkbench workbench)
	{
	}

	@Override
	protected Control createContents(final Composite parent)
	{
		Group syncListGroup = new Group(parent, 0);
		syncListGroup.setLayoutData(new GridData(4, 4, true, true, 2, 1));
		syncListGroup.setText("SyncFileList");

		GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 2;
		syncListGroup.setLayout(gridLayout);

		syncList = new org.eclipse.swt.widgets.List(syncListGroup, 2050);
		syncList.setLayoutData(new GridData(4, 4, true, true, 1, 12));

		this.addBut = new Button(syncListGroup, 0);
		this.addBut.setText("Add");
		this.addBut.addSelectionListener(new SelectionAdapter(){

			@Override
			public void widgetSelected(SelectionEvent e)
			{
				ContainerSelectionDialog dialog = new ContainerSelectionDialog(parent.getShell(), null, true, "");
				if(dialog.open() == ContainerSelectionDialog.OK)
				{
					Object[] result = dialog.getResult();
					if(result != null)
					{
						for(Object path : result)
						{
							syncList.add(path.toString());
						}
					}
				}
			}
		});

		this.removebut = new Button(syncListGroup, 0);
		this.removebut.setText("Remove");
		this.removebut.addSelectionListener(new SelectionAdapter(){

			@Override
			public void widgetSelected(SelectionEvent e)
			{
				syncList.remove(syncList.getSelectionIndices());
			}
		});

		SuRenPref suRenPref = new SuRenPref();
		for(String path : suRenPref.getSyncList())
		{
			syncList.add(path);
		}

		return null;
	}

	@Override
	public boolean performOk()
	{
		String[] syncFileArray = syncList.getItems();

		return new SuRenPref().setSyncList(syncFileArray);
	}
}
